package com.zzr.demo.rabbitmq.service.impl;

import com.rabbitmq.client.Channel;
import com.zzr.demo.rabbitmq.model.Person;
import com.zzr.demo.rabbitmq.service.ListenerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/8/25
 * @description:
 */
@Service("singleRabbitListenerService")
@Slf4j
public class SingleRabbitListenerServiceImpl implements ListenerService {

    /**
     * 1、使用 Object 接收
     * 监听队列：empty.queue
     * NOTEME 如果监听一个不存在的队列，就会异常！
     */
    @RabbitListener(queues = {"empty.queue"})
    public void receiveMessageInAtguigu(Object message) {
        //org.springframework.amqp.core.Message
        log.info("接收到消息，内容为：{}；类型为：{}", message, message.getClass());
    }


    /**
     * 2、发现具体的 class 后，使用 Message 进行接收
     * 监听队列：sample1-java-queue
     *
     * @param message
     */
    @RabbitListener(queues = {"empty.queue"})
    //@RabbitListener(queues = {"sample1-java-queue"})
    public void receiveMessageInSample1(Message message) {
        byte[] body = message.getBody();
        //各种消息体
        MessageProperties properties = message.getMessageProperties();
        log.info("接收到消息，内容为：{}，类型为：{}", message, message.getClass());
        log.info("消息体：{}", new String(body));
    }


    /**
     * 2、发现 new String(body ) 太麻烦了。于是使用 Person 居然可以直接接收消息体！Spring 自动转化！
     *
     * @param message
     */
    //@RabbitListener(queues = {"sample1-java-queue"})
    @RabbitListener(queues = {"empty.queue"})
    public void receiveMessageInSample1V2(Message message, Person person) {
        log.info("coming receiveMessageInSample1V2...");
        //各种消息体
        MessageProperties properties = message.getMessageProperties();
        log.info("接收到消息，内容为：{}，类型为：{}", message, message.getClass());
        log.info("消息体：{}", person);
    }

    /**
     * 3、当需要信道信息时，也可以直接得到！
     * Channel channel: 当前传输数据的通道
     * print:Cached Rabbit Channel: AMQChannel(amqp://guest@192.168.56.10:5672/,2), conn: Proxy@2032e725 Shared Rabbit Connection: SimpleConnection@67001148 [delegate=amqp://guest@192.168.56.10:5672/, localPort= 6283];
     * <p>
     * Queue:多个监听者；只要收到，队列就删除；只有一个接收者。
     * NOTEME:在单个监听方法中，没有处理完当前信息，也不会接收新的消息。（阻塞）
     *
     * @param message
     * @param person
     */
    //@RabbitListener(queues = {"sample1-java-queue"})
    @RabbitListener(queues = {"empty.queue"})
    public void receiveMessageInSample1V3(Message message, Person person, Channel channel) {
        log.info("coming receiveMessageInSample1V3...");
        //各种消息体
        MessageProperties properties = message.getMessageProperties();
        log.info("接收到消息，内容为：{}，类型为：{}", message, message.getClass());
        log.info("消息体：{}", person);
        log.info("信道：{};", channel);
    }

}
